<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html>
    
    <head>
        <title>Turbulenz - Getting Started Guide - API Example</title>
        <script src="jslib/debug.js"></script>
        <script src="jslib/webgl/turbulenzengine.js"></script>
        <script src="jslib/webgl/graphicsdevice.js"></script>
        <script src="jslib/webgl/inputdevice.js"></script>
        <script src="jslib/draw2d.js"></script>
        <script src="jslib/canvas.js"></script>
        <script src="jslib/utilities.js"></script>
        <script src="jslib/textureeffects.js"></script>
        <script src="jslib/fontmanager.js"></script>
        <script src="jslib/requesthandler.js"></script>
        <script src="jslib/observer.js"></script>
        <script type="text/javascript" src="./TextureFactory.js"></script>
        <script type="text/javascript" src="./JsonDummy.js"></script>
        <script type="text/javascript" src="./fpsCounter.js"></script>
        <script type="text/javascript" src="./sprite.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script type="text/javascript">
            TurbulenzEngine = WebGLTurbulenzEngine.create({
                canvas: document.getElementById("canvas")
            });
        </script>
        <script src="jslib/vmath.js"></script>
    </head>
    
    <body>
        <div id="debugDiv">
            <span id="fpsCounter"></span>
            <span id="mouseXpos"></span>
            <span id="mouseYpos"></span>
            <span id="offsetX"></span>
            <span id="offsetY"></span>
            <span id="tileX"></span>
            <span id="tileY"></span>
            <span id="tileInfo"></span>
        </div>
        <div id="mousePosDiv"></div>
        <div>
            <canvas id="canvas" width="800px" height="600px" />
        </div>
        <script>
            TurbulenzEngine = WebGLTurbulenzEngine.create({
                canvas: document.getElementById("canvas")
            });

             //// Devices Init
            var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
            var mathDevice = TurbulenzEngine.createMathDevice({});
            var canvas = Canvas.create(graphicsDevice, mathDevice);
            var draw2D = Draw2D.create({
                graphicsDevice: graphicsDevice
            });

             //// Input Device
            var gameRunning = false;
            var mouseElement = document.getElementById("mousePosDiv");
            var mouseXpos = document.getElementById("mouseXpos");
            var mouseYpos = document.getElementById("mouseYpos");
            var inputDevice = TurbulenzEngine.createInputDevice({});
            var mouseX = 0;
            var mouseY = 0;
            var onMouseMove = function mouseMoveFn(x, y) {
                mouseX = x;
                mouseY = y;
            }

            var onMouseEnter = function mouseEnterFn() {
                gameRunning = true;
            }

            var onMouseLeave = function mouseLeaveFn() {
                gameRunning = false;
            }
            var onMouseUp = function mouseUpFn() {
                if (insideTileMap()) {
                    if (itemMap[tileNum] > 0) {
                        itemMap[tileNum] = 0;
                    } else {
                        itemMap[tileNum] = 1;
                    }
                }
            }

            var onMouseDown = function mouseDownFn() {
                if (insideTileMap()) {
                    if (itemMap[tileNum] > 0) {
                        // TODO används senare till drag n drop
                    }
                }
            }

            inputDevice.addEventListener('mouseover', onMouseMove);
            inputDevice.addEventListener('mouseenter', onMouseEnter);
            inputDevice.addEventListener('mouseleave', onMouseLeave);
            inputDevice.addEventListener('mouseup', onMouseUp);
            inputDevice.addEventListener('mousedown', onMouseDown);

             //// Debug Element Variables
            var fpsElement = document.getElementById("fpsCounter");
            var tileInfoElement = document.getElementById("tileInfo");
            var tileXspan = document.getElementById("tileX");
            var tileYspan = document.getElementById("tileY");
            var offSetXspan = document.getElementById("offsetX");
            var offsetYspan = document.getElementById("offsetY");

            var ctx = canvas.getContext('2d');
            var viewportRect = [0, 0, canvas.clientWidth, canvas.clientHeight];

             // Array with TileMap textures
            var tileArray = new Array();
            var texturePathsArray = [];

             ////// TileMap Variabels X = width Y = height
            var tileXCount;
            var tileYCount;
            var tileHeight;
            var tileWidth;
            var halfTileHeight;
            var halfTileWidth;
            var offsetMapX = 320;
            var offsetMapY = 196;

            var xPos = 0;
            var yPos = 0;

             ////// Scroll view Variables
            var scrollPosition = {
                x: 0,
                y: 0
            };

             ////// Color Variables
            var r = 1.0,
                g = 0.0,
                b = 0.0,
                a = 1.0;
            var bgColor = [r, g, b, a];
            var bgWhite = [1, 1, 1, a];
            var bgBlack = [0, 0, 0, a];

             // Arrays with Tiles
            var map = Array(3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 2, 2, 3, 3, 2, 2, 1, 1, 2, 2, 2, 2, 3, 3, 2, 2, 1, 1, 4, 4, 2, 2, 3, 3, 2, 1, 1, 1, 1, 1, 2, 2, 3, 3, 2, 2, 2, 1, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 6, 3, 3, 3, 6, 3, 5, 3);
            var itemMap = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

            var ItemArray = [];
             //// Inits the Json data by loading dummy and assigning global variables
            initJsonData();

            var sprite = Draw2DSprite.create({
                width: 64,
                height: 32,
                color: [1.0, 1.0, 1.0, 1.0],
                textureRectangle: [0, 0, 64, 32]
            });

            var ballSprite = Draw2DSprite.create({
                width: 16,
                height: 16,
                color: [1.0, 1.0, 1.0, 1.0],
                textureRectangle: [0, 0, 16, 16]
            });
            
            var bouncingBallSprite = Draw2DSprite.create({
                width: 32,
                height: 32,
                color: [1.0, 1.0, 1.0, 1.0],
                textureRectangle: [0, 0, 32, 32]
            });

            var backgroundSprite = Draw2DSprite.create({
                width: 640,
                height: 640,
                x: graphicsDevice.width / 2,
                y: graphicsDevice.height / 2,
                color: [1.0, 1.0, 1.0, 1.0],
            });

            var texture = graphicsDevice.createTexture({
                src: "./img/tilePositionAlpha.png",
                mipmaps: true,
                onload: function(texture) {
                    if (texture) {
                        sprite.setTexture(texture);
                        sprite.setTextureRectangle([0, 0, 64, texture.height]);
                    }
                }
            });

            var ballTexture = graphicsDevice.createTexture({
                src: "./img/ball.png",
                mipmaps: true,
                onload: function(texture) {
                    if (texture) {
                        ballSprite.setTexture(texture);
                        ballSprite.setTextureRectangle([0, 0, 16, 16]);
                    }
                }
            });
            
            var bouncingBallTexture = graphicsDevice.createTexture({
                src: "./img/BallSpriteSheet.png",
                mipmaps: true,
                onload: function(texture) {
                    if (texture) {
                        bouncingBallSprite.setTexture(texture);
                        bouncingBallSprite.setTextureRectangle([0, 0, 32, 32]);
                    }
                }
            });
            
            
            
            var ballAniSprite = new AnimatedSprite(bouncingBallTexture, 256, 256, 64,128,32,32,false,0.5, [0,1,2,3,4,5,6,7]);
            
            var ballAniSprite2 = new AnimatedSprite(bouncingBallTexture, 320, 320, 64,128,32,32,false,0.5, [0,1,2,3,4,5,6,7]);

             //==========================================================  
             // Method for moving view with mouse on canvas WIP
             //==========================================================

            function moveView() {
                if (gameRunning) {
                    if (mouseX <= (canvas.clientWidth - 50) && scrollPosition.x < (canvas.clientWidth / 2)) {
                        scrollPosition.x += 2;
                    }
                    if (mouseX >= 50 && scrollPosition.x > (-canvas.clientWidth / 2)) {
                        scrollPosition.x -= 2;
                    }
                    if (mouseY <= (canvas.clientHeight - 50) && scrollPosition.y < (canvas.clientHeight / 2)) {
                        scrollPosition.y += 2;
                    }
                    if (mouseY >= 50 && scrollPosition.y > (-canvas.clientHeight / 2)) {
                        scrollPosition.y -= 2;
                    }
                }
            }

            var xTile;
            var yTile;

            function mouseMoveView() {
                //                var xTile = Math.floor(((mouseX - offsetMapX) / 64 ) * 2);
                //                var yTile = Math.floor(((mouseY - offsetMapY + 32) / 64) * 2);

                // TODO värdena är inte helt perfekt. Ligger 3-4 pixlar fel beroende på axel. Städa upp!
                // TODO X-axis Ändra till dynamiska variabler 96 (64 + 32) är för justering på pixelnivå
                // TODO Y-axis Ändra till dynamiska variabler 16 (64 / 2 / 2) är för justering på pixelnivå. tileHeight är statisk och felaktig(64) Eftersom vi stödjer H64xW32 och H64xW64 (Power of 2) så varierar storleken. Ta värdet ifrån TileArray istället. Framtida Z-axis bör tas ifrån tileArray för att avgöra nivåskillnad(Bonus)

                xTile = Math.floor((((((mouseX - scrollPosition.x) - 96) / 2) - offsetMapX + mouseY) - scrollPosition.y) / halfTileWidth);
                tileXspan.innerHTML = "Tile x-Axis: " + xTile;

                yTile = Math.floor((((mouseY - scrollPosition.y) - 16) - (mouseX / 2) + (scrollPosition.x / 2)) / tileHeight);
                tileYspan.innerHTML = "Tile y-Axis: " + yTile;
            }

            var tileNum;

            function currentTileInfo() {
                tileNum = (xTile + (yTile * 10));
                if (insideTileMap()) {
                    tileInfoElement.innerHTML = "TileNumber: " + tileNum;
                } else {
                    tileInfoElement.innerHTML = "TileNumber: Outside of tileMap";
                }
            }

            function insideTileMap() {
                if (xTile < 0 || xTile >= tileXCount || yTile < 0 || yTile >= tileYCount) {
                    return false;
                }
                return true;
            }

            function update() {
                inputDevice.update();

                /* Begin render */
                mouseXpos.innerHTML = "Mouse X: " + mouseX;
                mouseYpos.innerHTML = "Mouse Y: " + mouseY;
                offSetXspan.innerHTML = "offset X: " + scrollPosition.x;
                offsetYspan.innerHTML = "offset Y: " + scrollPosition.y;

                if (graphicsDevice.beginFrame()) {
                    graphicsDevice.clear(bgBlack, 1.0);

                    ctx.beginFrame(graphicsDevice, viewportRect);
                    var tilePosition = 0;
                    for (y = 0; y < tileYCount; y++) {
                        for (x = 0; x < tileXCount; x++) {
                            var drawTile = map[y][x];
                            var currentTile = tileArray[drawTile];
                            xPos = (x - y) * (tileWidth / 2) + offsetMapX;
                            yPos = ((x + y) * (tileHeight / 2)) + offsetMapY;
                            ctx.drawImage(currentTile.texture,
                                currentTile.xCoord,
                                currentTile.yCoord,
                                currentTile.imageWidth,
                                currentTile.imageHeight,
                                xPos + scrollPosition.x,
                                yPos + scrollPosition.y - currentTile.imageMargin,
                                currentTile.imageWidth,
                                currentTile.imageHeight);

                            if (tilePosition == (tileNum) && insideTileMap()) {
                                sprite.x = xPos + scrollPosition.x + halfTileWidth;
                                sprite.y = yPos + scrollPosition.y + halfTileHeight - currentTile.zOffset;
                                ctx.drawImage(
                                    texture,
                                    xPos + scrollPosition.x,
                                    yPos + scrollPosition.y - currentTile.zOffset);
                            }

                            var hasTile = itemMap[tilePosition] > 0;
                            if (hasTile) {
                                var ballPosX = xPos + scrollPosition.x + 24;
                                var ballPosY = yPos + scrollPosition.y - currentTile.zOffset + 8;
                                ctx.drawImage(ballTexture,
                                    0,
                                    0,
                                    16,
                                    16,
                                    ballPosX,
                                    ballPosY,
                                    16,
                                    16);
                            }
                            tilePosition++;


                        }
                    }
                    //                    draw2D.begin('alpha');
                    //                    var i;
                    //                    for (i = 0; i < ItemArray.length; i++) {
                    //                        var renderableItem = ItemArray[i];
                    //                                            draw2D.drawSprite(renderableItem);
                    //                    }
                    //                    draw2D.end(); 

                    //// Mouse scrolling in view
                    moveView();
                    mouseMoveView();

                    //// Enable Fps Counter for debugging
                    enableFpsCounter();

                    currentTileInfo();
                    
                    ballAniSprite.update(1000 / 60);
                    ballAniSprite.render(ctx);
                    
                    ballAniSprite2.update(1000 / 60);
                    ballAniSprite2.render(ctx);
                    
                    ctx.endFrame();
                }
            }

            TurbulenzEngine.setInterval(update, 1000 / 60);
        </script>
    </body>

</html>